package com.mfw.springboot.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mfw.springboot.annotation.AuthCheck;
import com.mfw.springboot.common.BaseResponse;
import com.mfw.springboot.common.DataGroupByDateDTO;
import com.mfw.springboot.common.DeleteRequest;
import com.mfw.springboot.common.ErrorCode;
import com.mfw.springboot.common.Result;
import com.mfw.springboot.constant.UserConstant;
import com.mfw.springboot.exception.BusinessException;
import com.mfw.springboot.exception.ThrowUtils;
import com.mfw.springboot.model.dto.trainingPlan.TrainingPlanAddRequest;
import com.mfw.springboot.model.dto.trainingPlan.TrainingPlanEditRequest;
import com.mfw.springboot.model.dto.trainingPlan.TrainingPlanQueryRequest;
import com.mfw.springboot.model.dto.trainingPlan.TrainingPlanUpdateRequest;
import com.mfw.springboot.model.dto.trainingRule.TrainingRuleDto;
import com.mfw.springboot.model.entity.TrainingPlan;
import com.mfw.springboot.model.entity.User;
import com.mfw.springboot.model.vo.TrainingPlanVO;
import com.mfw.springboot.service.TrainingPlanService;
import com.mfw.springboot.service.UserService;
import com.mfw.springboot.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 训练计划接口
 *
 * @author mfw
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@RestController
@RequestMapping("/trainingPlan")
@Slf4j
public class TrainingPlanController {

    @Resource
    private TrainingPlanService trainingPlanService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建训练计划
     *
     * @param trainingPlanAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTrainingPlan(@RequestBody TrainingPlanAddRequest trainingPlanAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(trainingPlanAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        TrainingPlan trainingPlan = new TrainingPlan();
        BeanUtils.copyProperties(trainingPlanAddRequest, trainingPlan);
        List<TrainingRuleDto> ruleList = trainingPlanAddRequest.getRuleList();
        if (ruleList != null){
            trainingPlan.setRules(JSONUtil.toJsonStr(ruleList));
        }
        // 数据校验
        trainingPlanService.validTrainingPlan(trainingPlan, true);
        // 填充默认值
        User loginUser = userService.getLoginUser(request);
        trainingPlan.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = trainingPlanService.save(trainingPlan);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newTrainingPlanId = trainingPlan.getId();
        return Result.success(newTrainingPlanId);
    }

    /**
     * 删除训练计划
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTrainingPlan(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        TrainingPlan oldTrainingPlan = trainingPlanService.getById(id);
        ThrowUtils.throwIf(oldTrainingPlan == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldTrainingPlan.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = trainingPlanService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 更新训练计划（仅管理员可用）
     *
     * @param trainingPlanUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTrainingPlan(@RequestBody TrainingPlanUpdateRequest trainingPlanUpdateRequest) {
        if (trainingPlanUpdateRequest == null || trainingPlanUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        TrainingPlan trainingPlan = new TrainingPlan();
        BeanUtils.copyProperties(trainingPlanUpdateRequest, trainingPlan);
        List<TrainingRuleDto> ruleList = trainingPlanUpdateRequest.getRuleList();
        if (ruleList != null){
            trainingPlan.setRules(JSONUtil.toJsonStr(ruleList));
        }
        // 数据校验
        trainingPlanService.validTrainingPlan(trainingPlan, false);
        // 判断是否存在
        long id = trainingPlanUpdateRequest.getId();
        TrainingPlan oldTrainingPlan = trainingPlanService.getById(id);
        ThrowUtils.throwIf(oldTrainingPlan == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = trainingPlanService.updateById(trainingPlan);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 根据 id 获取训练计划（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<TrainingPlanVO> getTrainingPlanVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        TrainingPlan trainingPlan = trainingPlanService.getById(id);
        ThrowUtils.throwIf(trainingPlan == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return Result.success(trainingPlanService.getTrainingPlanVO(trainingPlan, request));
    }

    /**
     * 分页获取训练计划列表（仅管理员可用）
     *
     * @param trainingPlanQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<TrainingPlan>> listTrainingPlanByPage(@RequestBody TrainingPlanQueryRequest trainingPlanQueryRequest) {
        long current = trainingPlanQueryRequest.getCurrent();
        long size = trainingPlanQueryRequest.getPageSize();
        // 查询数据库
        Page<TrainingPlan> trainingPlanPage = trainingPlanService.page(new Page<>(current, size),
                trainingPlanService.getQueryWrapper(trainingPlanQueryRequest));
        return Result.success(trainingPlanPage);
    }

    /**
     * 分页获取训练计划列表（封装类）
     *
     * @param trainingPlanQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<TrainingPlanVO>> listTrainingPlanVOByPage(@RequestBody TrainingPlanQueryRequest trainingPlanQueryRequest,
                                                               HttpServletRequest request) {
        long current = trainingPlanQueryRequest.getCurrent();
        long size = trainingPlanQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<TrainingPlan> trainingPlanPage = trainingPlanService.page(new Page<>(current, size),
                trainingPlanService.getQueryWrapper(trainingPlanQueryRequest));
        // 获取封装类
        return Result.success(trainingPlanService.getTrainingPlanVOPage(trainingPlanPage, request));
    }

    /**
     * 分页获取当前登录用户创建的训练计划列表
     *
     * @param trainingPlanQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<TrainingPlanVO>> listMyTrainingPlanVOByPage(@RequestBody TrainingPlanQueryRequest trainingPlanQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(trainingPlanQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        trainingPlanQueryRequest.setUserId(loginUser.getId());
        long current = trainingPlanQueryRequest.getCurrent();
        long size = trainingPlanQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<TrainingPlan> trainingPlanPage = trainingPlanService.page(new Page<>(current, size),
                trainingPlanService.getQueryWrapper(trainingPlanQueryRequest));
        // 获取封装类
        return Result.success(trainingPlanService.getTrainingPlanVOPage(trainingPlanPage, request));
    }

    /**
     * 编辑训练计划（给用户使用）
     *
     * @param trainingPlanEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editTrainingPlan(@RequestBody TrainingPlanEditRequest trainingPlanEditRequest, HttpServletRequest request) {
        if (trainingPlanEditRequest == null || trainingPlanEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        TrainingPlan trainingPlan = new TrainingPlan();
        BeanUtils.copyProperties(trainingPlanEditRequest, trainingPlan);
        // 数据校验
        trainingPlanService.validTrainingPlan(trainingPlan, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = trainingPlanEditRequest.getId();
        TrainingPlan oldTrainingPlan = trainingPlanService.getById(id);
        ThrowUtils.throwIf(oldTrainingPlan == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldTrainingPlan.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = trainingPlanService.updateById(trainingPlan);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
    * 日新增统计训练计划
    *
    * @return
    */
    @PostMapping("/day/newly/added")
    public BaseResponse<List<DataGroupByDateDTO>> dayNewlyAddedTrainingPlan() {
        // 今天
        Date endDate = DateUtils.getNow();
        // 30天以前
        Date beginDate = DateUtils.dayAfter(endDate, -30);
        // 查询
        List<DataGroupByDateDTO> trainingPlanDataList = trainingPlanService.countByDay(beginDate, endDate);
        //返回结果
        return Result.success(trainingPlanDataList);

    }

    // endregion
}
